import { _decorator, Component, Label, Node, Size, tween, Tween, UIOpacity, Vec3 } from 'cc';
import { ColorItem } from './ColorItem';
import { GameModel } from './GameModel';
import { PoolElementType } from '../Config/GameEnum';
import { GameColor } from '../Model/GameColor';
import { AudioManager } from '../../Basic/Manager/AudioManager';
import { SoundCode } from '../../Basic/Config/BaseEnum';
import { UnlockItemModel } from '../UnlockItem/UnlockItemModel';
const { ccclass, property } = _decorator;

@ccclass('GridItem')
export class GridItem extends Component {
  @property(Node)
  bg: Node;
  @property(Node)
  light: Node;
  @property(Node)
  colorParent: Node;
  @property(Node)
  selfBtn: Node;
  @property(Node)
  unlockBtn: Node;
  @property(Label)
  goldLab: Label;
  colorItem: ColorItem[] = [];
  colorData: GameColor[] = [];
  col: number;
  row: number;

  /** 设置单元格数据 */
  setData(colorData: GameColor[] = []) {
    while (this.colorData.length) this.colorData.pop();
    colorData.forEach((color) => {
      if (color.colorId === undefined) color.colorId = 'random';
    });
    if (colorData.length > 0) {
      this.colorData = [...colorData.splice(0)];
      if (this.colorData[0].colorId === 'random') this.colorData = [...GameModel.Ins().getItemData(this.col, this.row)];
    } else {
      this.colorData = [new GameColor('-1', ...[0, 1, 2, 3])];
    }
    this.colorData.sort((a, b) => a.posArr[0] - b.posArr[0]);
    this.colorParent.getComponent(UIOpacity).opacity = 255;
  }

  reset() {
    while (this.colorItem.length) {
      const item = this.colorItem.pop();
      item.reset();
      GameModel.Ins().cellMachine.poolFac.push(item.node);
    }
    while (this.colorData.length) this.colorData.pop();
    this.colorItem = [];
    this.colorData = [];
    this.row = -1;
    this.col = -1;
    this.selfBtn.active = false;
    this.light.active = false;
    this.colorParent.getComponent(UIOpacity).opacity = 255;
  }

  /** 设置位置信息 */
  setIndex(col: number, row: number) {
    this.col = col;
    this.row = row;
  }

  /** 根据位置获取对应颜色 */
  getColor(colorPos: number) {
    for (let i = 0; i < this.colorData.length; i++) {
      if (this.colorData[i].posArr.indexOf(colorPos) !== -1) {
        return this.colorData[i].colorId;
      }
    }
    return '-1';
  }

  /** 根据位置获取对应颜色位置 */
  getColorIndex(colorPos: number) {
    for (let i = 0; i < this.colorData.length; i++) {
      if (this.colorData[i].posArr.indexOf(colorPos) !== -1) {
        return i;
      }
    }
    return -1;
  }

  protected onEnable(): void {
    this.bg.active = false;
    this.selfBtn.active = false;
    this.refrechColor();
  }

  showLight(isShow: boolean) {
    this.light.active = isShow;
  }

  /** 是否为空 */
  get isEmpty() {
    return this.colorData.length === 1 && this.colorData[0].colorId === '-1';
  }
  /** 是否为裂缝 */
  get isCrack() {
    return this.colorData.length === 1 && this.colorData[0].colorId === 'obstacle_crack';
  }
  /** 是否为箱子 */
  get isBox() {
    return this.colorData.length === 1 && this.colorData[0].colorId === 'obstacle_box';
  }
  /** 是否为禁用 */
  get isDisable() {
    return this.colorData.length === 1 && this.colorData[0].colorId === 'obstacle_disable';
  }

  /** 刷新颜色 */
  refrechColor(isTween: boolean = false) {
    this.unlockBtn.active = this.isCrack;

    let space = this.colorData.length - this.colorItem.length;
    if (space < 0) {
      space = Math.abs(space);
      for (let i = 0; i < space; i++) GameModel.Ins().cellMachine.poolFac.push(this.colorItem.pop().node);
    } else if (space > 0) {
      for (let i = 0; i < space; i++) {
        const item = GameModel.Ins().cellMachine.poolFac.pop(PoolElementType.COLOR_ITEM, 'maingame/game', 'ColorItem');
        Tween.stopAllByTarget(item);
        const script = item.getComponent(ColorItem);
        script.reset();
        this.colorItem.push(script);
        this.colorParent.addChild(item);
        item.active = true;
      }
    }

    const itemSize = GameModel.Ins().itemSize;

    for (let i = 0; i < this.colorData.length; i++) {
      const script = this.colorItem[i];
      const item = script.node;
      // console.log(item.getPosition().clone());

      script.setColor(this.colorData[i].colorId, this.col, this.row);
      const endPos = new Vec3();
      const size = new Size();
      const endScale = new Vec3(1, 1, 1);
      // [橙 紫 蓝 紫] [ 0, [1,3], 2] => [[0,2] [1, 3]]
      if (this.colorData[i].posArr.length >= 4) {
        endPos.x = 0;
        endPos.y = 0;
        endScale.x = 1;
        endScale.y = 1;
        size.width = itemSize.width;
        // size.height = itemSize.height / 2 + itemSize.width / 2;
        size.height = Math.pow(itemSize.height / 2 + itemSize.width / 2, 2) / itemSize.width;
      } else if (this.colorData[i].posArr.length >= 2) {
        // 判断横向还是纵向
        let posX = 0;
        let posY = 0;
        endScale.x = 0.75;
        endScale.y = 0.75;
        if (Math.abs(this.colorData[i].posArr[1] - this.colorData[i].posArr[0]) === 1) {
          // 横向
          size.width = itemSize.width;
          size.height = ((itemSize.height / 2) * itemSize.height) / itemSize.width;
          posY = this.colorData[i].posArr[0] === 0 ? itemSize.width / 4 : -itemSize.width / 4;
        } else {
          // 纵向
          size.width = itemSize.width / 2;
          size.height = Math.pow(itemSize.height / 2 + itemSize.width / 2, 2) / itemSize.width;
          posX = this.colorData[i].posArr[0] === 0 ? -itemSize.width / 4 : itemSize.width / 4;
        }
        endPos.x = posX;
        endPos.y = posY;
      } else {
        // 单个色块
        endScale.x = 0.5;
        endScale.y = 0.5;
        endPos.x = ((-1 / 2) * itemSize.width) / 2 + ((this.colorData[i].posArr[0] % 2) * itemSize.width) / 2;
        endPos.y = ((1 / 2) * itemSize.width) / 2 - (Math.floor(this.colorData[i].posArr[0] / 2) * itemSize.width) / 2;
        size.width = itemSize.width / 2;
        size.height = ((itemSize.height / 2) * itemSize.height) / itemSize.width;
      }
      Tween.stopAllByTarget(item);
      Tween.stopAllByTarget(script);
      Tween.stopAllByTarget(script.icon.node);
      if (isTween) {
        tween(item).to(GameModel.Ins().cellMachine.shapeChange, { position: endPos }).start();
        tween(script).to(GameModel.Ins().cellMachine.shapeChange, { Width: size.width, Height: size.height }).start();
        tween(script.icon.node).to(GameModel.Ins().cellMachine.shapeChange, { scale: endScale }).start();
      } else {
        script.Width = size.width;
        script.Height = size.height;
        item.setPosition(endPos);
        script.icon.node.scale = endScale;
      }
    }
  }

  resetDestory() {
    this.colorItem.forEach((item) => {
      item.destroyFlag = false;
    });
  }

  tryRemoveColor() {
    // 移除颜色的下标
    const ret = [];
    if (this.isDisable || this.isCrack || this.isEmpty) return ret;
    let removeIndex = 0;
    for (let i = 0; i < this.colorItem.length; i++) {
      const item = this.colorItem[i];
      if (item.destroyFlag) {
        GameModel.Ins().cellMachine.addRemoveColorItem(item);
        // GameModel.Ins().addReduceData(this.colorData[i].colorId, 1);
        // GameModel.Ins().cellMachine.flyPos.push({ color: item.curColor, wPos: item.node.getWorldPosition().clone() });
        // GameModel.Ins().cellMachine.playEffect('splash', item.node.getWorldPosition().clone(), item.curColor);
        // GameModel.Ins().addGameMoney(DataMgr.tables.TbColor.get(item.curColor).value, item.node.getWorldPosition().clone());
        ret.push(i + removeIndex);
        this.colorItem.splice(i, 1);
        i--;
        removeIndex++;
        // item.reset();
        // Tween.stopAllByTarget(item);
        // GameModel.Ins().cellMachine.poolFac.push(item.node);
      }
    }
    if (ret.length <= 0) return ret;

    // 处理移除之后的位置数据
    const emptyPos = [];
    ret.forEach((index) => {
      this.colorData[index].posArr.forEach((index) => emptyPos.push(index));
    });
    emptyPos.sort((a, b) => a - b);

    for (let i = 0; i < this.colorData.length; i++) {
      let temp = false;
      this.colorData[i].posArr.forEach((pos) => {
        if (emptyPos.indexOf(pos) != -1) {
          temp = true;
        }
      });
      if (temp) {
        this.colorData.splice(i, 1).shift();
        i--;
      }
    }

    if (this.colorData.length <= 0) {
      this.colorData.push(new GameColor('-1', ...[0, 1, 2, 3]));
      const retData = [...this.colorData];
      this.setData(retData);
    } else if (emptyPos.length > 0) {
      // 全部填充
      // const sortIndex = [0, 2, 1, 3];
      // 执行顺序 0-2-1-3
      // this.colorData.sort((a, b) => sortIndex[a.posArr[0]] - sortIndex[b.posArr[0]]);

      this.colorData.forEach((item) => {
        if (item.posArr.length === 1) {
          if (emptyPos.length === 3) {
            item.posArr.push(...emptyPos);
            item.posArr.sort((a, b) => a - b);
          } else {
            // 上下填充
            const up = item.posArr[0] - 2;
            const down = item.posArr[0] + 2;
            // const left = item.posArr[0] - 1;
            // const right = item.posArr[0] + 1;
            if ([0, 1].indexOf(up) !== -1 && emptyPos.indexOf(up) !== -1) {
              item.posArr.push(...emptyPos.splice(emptyPos.indexOf(up), 1));
            } else if ([2, 3].indexOf(down) !== -1 && emptyPos.indexOf(down) !== -1) {
              item.posArr.push(...emptyPos.splice(emptyPos.indexOf(down), 1));
            }
            //  else if ([0, 2].indexOf(left) !== -1 && emptyPos.indexOf(left) !== -1) {
            //   item.posArr.push(...emptyPos.splice(emptyPos.indexOf(left), 1));
            // } else if ([1, 3].indexOf(right) !== -1 && emptyPos.indexOf(right) !== -1) {
            //   item.posArr.push(...emptyPos.splice(emptyPos.indexOf(right), 1));
            // }
          }

          item.posArr.sort((a, b) => a - b);
          // 其次左右
        } else if (emptyPos.length === 2) {
          item.posArr.push(...emptyPos);
          item.posArr.sort((a, b) => a - b);
        }
      });
      this.colorData.forEach((item) => {
        if (item.posArr.length === 1) {
          if (emptyPos.length === 3) {
            item.posArr.push(...emptyPos);
            item.posArr.sort((a, b) => a - b);
          } else {
            // 左右填充
            // const up = item.posArr[0] - 2;
            // const down = item.posArr[0] + 2;
            const left = item.posArr[0] - 1;
            const right = item.posArr[0] + 1;
            // if ([0, 1].indexOf(up) !== -1 && emptyPos.indexOf(up) !== -1) {
            //   item.posArr.push(...emptyPos.splice(emptyPos.indexOf(up), 1));
            // } else if ([2, 3].indexOf(down) !== -1 && emptyPos.indexOf(down) !== -1) {
            //   item.posArr.push(...emptyPos.splice(emptyPos.indexOf(down), 1));
            // }
            if ([0, 2].indexOf(left) !== -1 && emptyPos.indexOf(left) !== -1) {
              item.posArr.push(...emptyPos.splice(emptyPos.indexOf(left), 1));
            } else if ([1, 3].indexOf(right) !== -1 && emptyPos.indexOf(right) !== -1) {
              item.posArr.push(...emptyPos.splice(emptyPos.indexOf(right), 1));
            }
          }

          item.posArr.sort((a, b) => a - b);
          // 其次左右
        } else if (emptyPos.length === 2) {
          item.posArr.push(...emptyPos);
          item.posArr.sort((a, b) => a - b);
        }
      });

      // this.colorData.sort((a, b) => a.posArr[0] - b.posArr[0]);
      const retData = [...this.colorData];
      for (let i = 0; i < retData.length - 1; i++) {
        for (let j = 1; j < retData.length; j++) {
          if (retData[i].posArr[0] > retData[j].posArr[0]) {
            const tempData = retData[i];
            retData[i] = retData[j];
            retData[j] = tempData;

            const tempItem = this.colorItem[i];
            this.colorItem[i] = this.colorItem[j];
            this.colorItem[j] = tempItem;
          }
        }
      }
      // retData.sort((a, b) => a.posArr[0] - b.posArr[0]);
      this.setData(retData);
    }

    setTimeout(this.refrechColor.bind(this, true), GameModel.Ins().cellMachine.cleanSpeed * 1000);
    return ret;
  }

  unlockItem() {
    this.unlockBtn.active = false;
    this.setData([new GameColor(`-1`, ...[0, 1, 2, 3])]);
    this.refrechColor();
    GameModel.Ins().cellMachine.checkMachine();
  }

  onClickItem() {
    if (this.isEmpty || this.isBox || this.isCrack || this.isDisable || this.col === -1 || this.row === -1) return;
    AudioManager.Singleton.playSound(SoundCode.BTN_CLICK);
    if (GameModel.Ins().cellMachine.prop1Enable) {
      // 显示打包盒特效
      GameModel.Ins().cellMachine.prop1Enable = false;
      this.bg.active = true;
      GameModel.Ins().spineGrid = this.node;
      GameModel.Ins().cellMachine.playEffect('box', this.node.getWorldPosition().clone());
    }
  }

  onClickBtn(t: Touch, data) {
    if (!GameModel.Ins().cellMachine.releaseEnable) return;
    const key = data.toString();
    AudioManager.Singleton.playSound(SoundCode.BTN_CLICK);

    switch (key) {
      case 'unlock':
        UnlockItemModel.Ins().unlockCol = this.col;
        UnlockItemModel.Ins().unlockRow = this.row;
        UnlockItemModel.Ins().Show();
        break;
    }
  }
}
